// 和广告操作有关的路由；
const formidable = require("formidable");
const express = require("express");
const advModel = require("../models/advModel");
const router = express.Router();
const path = require("path");

let form = new formidable.IncomingForm({
    uploadDir: path.resolve(process.cwd(), "./static"),
    keepExtensions: true  
});

router.get("/adv",(req,res)=>{
    res.send("测试")
})

router.post("/addadv",(req,res)=>{
    form.parse(req,async(err,fields,files)=>{
        if(err){
            return console.log(err)
        }
        fields.addtime = new Date().toLocaleDateString();
        fields.imgurl = files.imgFile.newFilename;
        console.log(fields)
        try{
            await advModel.create(fields);
            res.json({
                info:"添加成功",
                status:1
            })
        }catch(err){
            console.log(err)
            res.json({
                info:"添加失败",
                status:0,
                err
            })
        }
    })
})

router.get("/getDatas",async (req,res)=>{
    let {p,perpage} = req.query;
    if(typeof p === "undefined"){
        p = 1;
    }
    if(typeof perpage === "undefined"){
        perpage = 3;
    }
    let totaldata = await advModel.find(); 
    let totalCount = totaldata.length;
    let pageCount = Math.ceil( totalCount/perpage); 

    let result  = await advModel.find(null,{addtime:1,imgurl:1,username:1}).skip((p-1)*perpage).limit(perpage);
    res.json({result,pageCount});
})

router.delete("/delData",async (req,res)=>{
    let {_id} = req.query;
    try{
        await advModel.deleteOne({_id});
        res.json({
            info:"删除成功",
            status:1
        })
    }catch(err){
        console.log(err);
        res.json({
            info:"删除失败",
            status:0,
            err
        })
    }
})
// router.post("/beData",(req,res)=>{
    
//     form.parse(req,async(err,fields,files)=>{
//         if(err){
//             return console.log(err)
//         }
//         fields.addtime = new Date().toLocaleDateString();
//         fields.imgurl = files.imgFile.newFilename;
//         console.log(fields._id)
//         try{
//             await advModel.updateOne({});
//             res.json({
//                 info:"添加成功",
//                 status:1
//             })
//         }catch(err){
//             console.log(err)
//             res.json({
//                 info:"添加失败",
//                 status:0,
//                 err
//             })
//         }
//     })
// })


module.exports = router;